package org.example.mp4demo.mp4;

import org.mp4parser.IsoFile;
import org.mp4parser.boxes.iso14496.part12.SchemeTypeBox;
import org.mp4parser.boxes.iso14496.part12.TrackBox;
import org.mp4parser.muxer.CencMp4TrackImplImpl;
import org.mp4parser.muxer.FileRandomAccessSourceImpl;
import org.mp4parser.muxer.Movie;
import org.mp4parser.muxer.RandomAccessSource;
import org.mp4parser.muxer.container.mp4.MovieCreator;
import org.mp4parser.tools.Path;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.ReadableByteChannel;
import java.util.List;

public class CustomMovieCreator extends MovieCreator {
    public static Movie build(String file) throws IOException {
        File f = new File(file);
        FileInputStream fis = new FileInputStream(f);
        Movie m = build(fis.getChannel(), new FileRandomAccessSourceImpl(new RandomAccessFile(f, "r")), file);
        fis.close();
        return m;
    }

    public static Movie build(ReadableByteChannel readableByteChannel, RandomAccessSource randomAccessSource, String name) throws IOException {
        IsoFile isoFile = new IsoFile(readableByteChannel);
        Movie m = new Movie();
        List<TrackBox> trackBoxes = isoFile.getMovieBox().getBoxes(TrackBox.class);
        for (TrackBox trackBox : trackBoxes) {
            SchemeTypeBox schm = Path.getPath(trackBox, "mdia[0]/minf[0]/stbl[0]/stsd[0]/enc.[0]/sinf[0]/schm[0]");
            if (schm != null && (schm.getSchemeType().equals("cenc") || schm.getSchemeType().equals("cbc1"))) {
                m.addTrack(new CencMp4TrackImplImpl(
                        trackBox.getTrackHeaderBox().getTrackId(), isoFile,
                        randomAccessSource, name + "[" + trackBox.getTrackHeaderBox().getTrackId() + "]"));
            } else {
                //默认类型的Mp4会进入到这里
                m.addTrack(new CustomMp4TrackImp(
                        trackBox.getTrackHeaderBox().getTrackId(), isoFile,
                        randomAccessSource, name + "[" + trackBox.getTrackHeaderBox().getTrackId() + "]"));
            }
        }
        m.setMatrix(isoFile.getMovieBox().getMovieHeaderBox().getMatrix());
        return m;
    }
}
